# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql


# 存本地O
class QiubaiPipeline:
    # 开始调用时运行一次
    def open_spider(self, spider):
        print('开始运行')
        self.fp = open('./qiubai.txt', 'w', encoding='utf-8')

    # 处理item,每接收item就被调用一次
    def process_item(self, item, spider):
        author = item['author']
        content = item['content']

        self.fp.write(author + ':' + content + '\n')
        # 返回后传给下一个即将执行的管道
        return item

        # 结束时调用

    def close_spider(self, spider):
        print('结束运行')
        self.fp.close()

    # 存数据库


class mysqlPipeLine(object):
    conn = None
    cursor = None

    def open_spider(self, spider):
        self.conn = pymysql.Connect('localhost', user="root", passwd="root", db="qiubai")

    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute('insert into qiubai values("%s","%s")' % (item["author"], item["content"]))
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()
